import { CellEditor, Column, EditorFactory as EditorFactoryType, EditorRegistry } from '../types'
import { TextEditor } from './TextEditor'
import { NumberEditor } from './NumberEditor'
import { DateTimeEditor } from './DateTimeEditor'
import { SelectEditor } from './SelectEditor'
import { TextAreaEditor } from './TextAreaEditor'
import { CheckboxEditor } from './CheckboxEditor'
import { ColorEditor } from './ColorEditor'

export class EditorFactory implements EditorRegistry {
  private static instance: EditorFactory
  private editors: Map<string, EditorFactoryType> = new Map()
  
  private constructor() {
    // 注册默认编辑器
    this.registerDefaultEditors()
  }
  
  static getInstance(): EditorFactory {
    if (!EditorFactory.instance) {
      EditorFactory.instance = new EditorFactory()
    }
    return EditorFactory.instance
  }
  
  // 注册编辑器
  register(type: string, factory: EditorFactoryType): void {
    this.editors.set(type, factory)
  }
  
  // 获取编辑器工厂
  get(type: string): EditorFactoryType | undefined {
    return this.editors.get(type)
  }
  
  // 检查是否有编辑器
  has(type: string): boolean {
    return this.editors.has(type)
  }
  
  // 创建编辑器
  createEditor(column: Column): CellEditor | null {
    const type = column.editType || 'text'
    
    // 如果有自定义编辑器，使用自定义编辑器
    if (column.customEditor) {
      return column.customEditor(column)
    }
    
    // 获取注册的编辑器工厂
    const factory = this.get(type)
    if (factory) {
      return factory(column)
    }
    
    // 默认使用文本编辑器
    console.warn(`Unknown editor type: ${type}, using text editor`)
    return new TextEditor(column)
  }
  
  // 注册默认编辑器
  private registerDefaultEditors(): void {
    // 文本编辑器
    this.register('text', (column) => new TextEditor(column))
    this.register('email', (column) => new TextEditor(column))
    this.register('url', (column) => new TextEditor(column))
    
    // 数字编辑器
    this.register('number', (column) => new NumberEditor(column))
    
    // 日期时间编辑器
    this.register('date', (column) => new DateTimeEditor(column))
    this.register('time', (column) => new DateTimeEditor(column))
    this.register('datetime', (column) => new DateTimeEditor(column))
    
    // 下拉选择编辑器
    this.register('select', (column) => new SelectEditor(column))
    
    // 多行文本编辑器
    this.register('textarea', (column) => new TextAreaEditor(column))
    
    // 复选框编辑器
    this.register('checkbox', (column) => new CheckboxEditor(column))
    
    // 颜色选择器
    this.register('color', (column) => new ColorEditor(column))
  }
}

// 导出单例实例
export const editorFactory = EditorFactory.getInstance() 